import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/TabContainerWidget/TabContainerWidget.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/ui.dart';
import 'package:orginone/dart/core/chat/session.dart';
import 'package:orginone/dart/core/public/entity.dart';
import 'package:orginone/routers/app_route.dart';
import 'package:orginone/routers/index.dart';
import 'package:orginone/utils/log/log_util.dart';
import 'package:provider/provider.dart';
import '../../dart/base/common/commands.dart';
import '../../dart/base/common/emitter.dart';
import '../../main.dart';
import '../../pages/home/components/BadgeTabWidget/BadgeTabWidget.dart';
import '../CommandWidget/index.dart';
import '../PortalManagerWidget/portalrefresh_event.dart';
import '../XConsumer/XConsumer.dart';
import '../XScaffold/XScaffold.dart';

/// 静态组件
abstract class XStatelessWidget<P> extends StatelessWidget with _Controller<P>, EmitterMixin {
  late P _data;
  late final dynamic entity;
  AppRoute? routeData;

  P get data => _data;

  XStatelessWidget({super.key, this.routeData, data}) {
    _data =
        data ?? RoutePages.getRouteParams() ?? RoutePages.getParentRouteParam();
    this.entity = RoutePages.getParentRouteParam();
  }

  @override
  Widget build(BuildContext context) {
    AppRoute? rd = fromRoute(context);
    _data ??= rd?.currPageData.data;
    return _build(context, routeData ?? rd ?? AppRoute(), _data, entity);
  }
}

/// 动态组件
abstract class XStatefulWidget<P> extends StatefulWidget {
  late final P data;
  late final dynamic entity;
  AppRoute? routeData;

  XStatefulWidget({super.key, this.routeData, data}) {
    this.data =
        data ?? RoutePages.getRouteParams() ?? RoutePages.getParentRouteParam();
    this.entity = RoutePages.getParentRouteParam();
  }
}

abstract class XStatefulState<T extends XStatefulWidget<P>, P> extends State<T>
    with _Controller<P> {
  late P data;
  dynamic get entity => widget.entity;
  AppRoute? get routeData => widget.routeData;

  @override
  void initState() {
    super.initState();
    data = widget.data;
    // key = command.subscribeByFlag("homeChange", ([List<dynamic>? args]) {
    //   LogUtil.d("did homeChange 1");
    //   if (mounted) {
    //     setState(() {});
    //   }
    // });
    // LogUtil.d("======== did initState $key");
    // loadCurrSpace();
  }

  // @override
  // didChangeDependencies() {
  //   super.didChangeDependencies();
  //   LogUtil.d("didChangeDependencies");
  //   // LogUtil.d("======== did $key");
  // }

  @override
  void dispose() {
    super.dispose();
    // command.unsubscribeByFlag(key);
    // LogUtil.d("======== did dispose $key");
    // command.emitter('chat', 'new');
    // portalRefreshEventBus.fire(PortalRefreshEvent(-1));
  }

  @override
  Widget build(BuildContext context) {
    AppRoute? rd = fromRoute(context);
    data ??= rd?.currPageData.data;
    return _build(context, routeData ?? rd ?? AppRoute(), data, entity);
  }
}

mixin _Controller<P> {
  AppRoute? fromRoute(BuildContext context) {
    ModalRoute<dynamic>? route = ModalRoute.of(context);
    AppRoute? rd;
    if (null != route && route.settings.arguments is AppRoute) {
      rd = route.settings.arguments as AppRoute;
    } else {
      try {
        rd = context.read<AppRoute>();
      } catch (e) {}
    }
    return rd;
  }

  Widget _build(
      BuildContext context, AppRoute routeData, P data, dynamic paramData) {
    return WillPopScope(
        onWillPop: () async {
          if (!RoutePages.isHomePage()) {
            RoutePages.back(context);
            return false;
          }
          return true;
        },
        child: _buildPage(context, data, paramData));
  }

  Widget _buildPage(BuildContext context, P data, dynamic paramData) {
    Widget body = buildWidget(context, data);
    bool hasTabs = _hasChildOfType(body, TabContainerWidget);
    return XScaffold(
        // backgroundColor: Colors.white,
        // titleName: data.name ?? "详情",
        titleWidget: _title(context),
        isHomePage: isHomePage(context),
        parentRouteParam:
            isHomePage(context) ? null : RoutePages.getParentRouteParam(),
        centerTitle: false,
        titleSpacing: 0,
        leadingWidth: 35,
        // actions: [XImage.localImage(XImage.user)],
        // leading: XImage.localImage(XImage.user),
        operations: buildButtons(context, data),
        // toolbarHeight: _getToolbarHeight(data),
        drawer: buildDrawer(context),
        body: Container(
          color: const Color(0xFFF0F0F0),
          margin: hasTabs ? null : EdgeInsets.symmetric(vertical: 1.h),
          decoration: hasTabs ? null : const BoxDecoration(color: Colors.white),
          child: body,
        ));
  }

  bool isHomePage(BuildContext context) {
    AppRoute rd = context.watch<AppRoute>();
    return rd.isHomePage();
  }

  void openDrawer(BuildContext context) {
    Scaffold.of(context).openDrawer();
  }

  bool _hasChildOfType<T>(Widget widget, T type) {
    if (widget.runtimeType is T) {
      return true;
    }
    if (widget is Column) {
      if (widget.children.isEmpty) {
        return false;
      }

      for (var child in widget.children) {
        if (_hasChildOfType(child, type)) {
          return true;
        }
      }
    }

    return false;
  }

  double? _getToolbarHeight(P data) {
    var spaceName = "";
    if (data is IEntity) spaceName = data.groupTags.join(" | ");
    if (spaceName.isNotEmpty) {
      return 78.h;
    }
    return null;
  }

  Widget _title(BuildContext context) {
    var isHome = isHomePage(context);
    return XConsumer<AppRoute>(
      builder: (context, rd, child) {
        var entity = rd.currPageData.entity;
        String name = rd.currPageData.title ?? entity?.name ?? "";
        XLogUtil.dd('>>>>>> title $name');
        return GestureDetector(
            onTap: () {
              onTapTitle(context);
            },
            child: DefaultTextStyle(
                maxLines: 1,
                style: XFonts.size26Black3
                    .merge(const TextStyle(overflow: TextOverflow.ellipsis)),
                child: Row(
                  children: [
                    (null == entity && entity is FileItemShare)
                        ? Container()
                        : _buildAvatar(context, entity),
                    Expanded(
                        flex: rd.hasMore ? 0 : 1,
                        child: Container(
                          padding: const EdgeInsets.only(left: 5, right: 5),
                          width: name.length > 6
                              ? rd.hasMore
                                  ? 240
                                  : null
                              : null,
                          child: Text.rich(TextSpan(children: [
                            WidgetSpan(
                                child: Text(
                              name,
                            )),
                          ])),
                          // Padding(
                          //     padding: const EdgeInsets.only(top: 2),
                          //     child: Text(spaceName, style: XFonts.size16Black9)),
                        )),
                    Padding(
                      padding: const EdgeInsets.only(right: 5),
                      child: getSubTitle(context, entity),
                    ),
                    if (rd.hasMore)
                      Container(
                          margin: EdgeInsets.only(left: 10.w),
                          child: XImage.localImage(XImage.more)),
                  ],
                )));
      },
    );
  }

  Widget getSubTitle(BuildContext context, IEntityUI? entity) {
    int memberCount = 0;
    if (entity is ISession) {
      memberCount = entity.memberCount;
    }
    return Text(memberCount > 0 ? '($memberCount)' : '');
  }

  Widget _buildAvatar(BuildContext context, IEntityUI? entity) {
    return isHomePage(context)
        ? CommandWidget<List<dynamic>>(
            type: 'connection',
            cmd: 'state',
            builder: (context, args) {
              args ??= [kernel.isOnline, kernel.online];
              return Padding(
                  padding: const EdgeInsets.only(left: 5, right: 5),
                  child: BadgeTabWidget(
                      body: XImage.entityIcon(entity, width: 40.w),
                      mgsCount: -1,
                      badgeColor: args[1] == '在线'
                          ? Colors.blue
                          : args[1] == '连线'
                              ? Colors.yellow
                              : Colors.red));
            })
        : XImage.entityIcon(entity, width: 40.w);
  }

  @protected
  List<Widget>? buildButtons(BuildContext context, P data) {
    return null;
  }

  Widget? buildDrawer(BuildContext context) {
    return null;
  }

  @protected
  void Function()? onTapTitle(BuildContext context) {
    return null;
  }

  @protected
  Widget buildWidget(BuildContext context, P data);
}
